<?php

namespace controller\admin;

defined('IA_ROOT') || exit();

use facade\Model;
use facade\View;
use facade\Util;

// 日志管理
class log extends Base
{
    // 列表
    public function index()
    {
        if (Util::isAjax()) {
            $param = Util::param();
            $start = ($param['page'] - 1) * $param['limit'];
            $limit = $param['limit'];
            // $where = "`id` <= (SELECT `id` FROM `log` ORDER BY `id` DESC LIMIT $start, 1)";
            $where = "1 = 1";
            // 搜索
            if (!empty($param['search'])) {
                foreach ((array)$param['search'] as $k => $v) {
                    if (strlen($v)) {
                        if (in_array($k, ['request_method', 'status'])) {
                            $where .= " AND `$k` = '$v'";
                        } else if (in_array($k, ['start', 'end'])) {
                            $timestamp = strtotime($v);
                            if ($k == 'start')
                                $where .= " AND `create_at` >= '$timestamp'";
                            else
                                $where .= " AND `create_at` <= '$timestamp'";
                        } else {
                            $where .= " AND `$k` like '%{$v}%'";
                        }
                    }
                }
            }
            $count = Model::fetchColumn("SELECT COUNT(*) FROM `log` WHERE $where ORDER BY `id` DESC");
            $data = Model::fetchAll("SELECT * FROM `log` WHERE $where ORDER BY `id` DESC LIMIT $start, $limit");
            if ($count) {
                $res['code'] = 0;
            } else {
                $res['code'] = 1;
                $res['msg'] = '暂无记录';
            }
            $res['count'] = $count;
            $res['data'] = array_map(function ($item) {
                $item['time'] = date('Y-m-d H:i', $item['time']);
                return $item;
            }, $data);
            exit(json_encode($res));
        }
        View::display('admin/log/index.html');
    }

    // 删除
    public function delete()
    {
        $param = Util::param(['id']);
        (empty($param) || !isset($param['id'])) && Util::errMsg('请选择数据');
        $idStr = implode(',', (array)$param['id']);
        $names = Model::fetchAll("SELECT `title` FROM `log` WHERE `id` IN ($idStr)");
        $names = array_map(function ($item) {
            return $item['title'];
        }, $names);

        // 删除数据记录日志
        $rowCount = Model::delete('log', ['id' => $param['id']]);
        if ($rowCount)
            Util::errMsg(['code' => 0, 'msg' => '删除成功']);
        else
            Util::errMsg(['code' => 1, 'msg' => '删除失败']);
    }
}
